package com.linlong.linlongchat.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.linlong.linlongchat.domain.po.Result;
import com.linlong.linlongchat.domain.po.User;
import com.linlong.linlongchat.mapper.UserMapper;
import com.linlong.linlongchat.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linlong.linlongchat.utils.JwtUtil;
import com.linlong.linlongchat.utils.Md5Util;
import com.linlong.linlongchat.utils.StringToolsUtil;
import com.linlong.linlongchat.utils.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 华少
 * @since 2024-09-19
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired(required = false)
    private JavaMailSender javaMailSender;
    @Autowired
    private VerifyCodeUtil verifyCodeUtil;
    @Override
    public Result<String> login(String username, String password) {
        //检查用户名是否存在
        User user = userMapper.selectByUsername(username);
        if(user != null) {
            return Result.fail("用户名已存在");
        }
        /**
         * 判断密码是否正确
         */
        if (Md5Util.getMD5String(password).equals(user.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            /**
             * 设置account和用户名
             */
            claims.put("account", user.getAccount());
            claims.put("id", user.getId());
            String token = JwtUtil.genToken(claims);

            //把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            /**
             *
             void set(K key, V value, long timeout, TimeUnit unit);
             */
            operations.set("token",token,1, TimeUnit.HOURS);
            return Result.ok(token);
        }
        return Result.fail("密码错误");
    }

    @Override
    public Result register(String nickName, String email, String code, String password) {
        //随机生成一个11位账号
        String account = StringToolsUtil.generateRandomAccount(11);
        if (null != userMapper.selectByAccount(account)) {
            return Result.fail("账号已存在");
            }
        //判断验证码是否正确
        String key = "code_" + email;
        String codeInRedis = stringRedisTemplate.opsForValue().get(key);
        if (codeInRedis == null) {
            return Result.fail("验证码已过期");
        }
        if (!code.equals(codeInRedis)) {
            return Result.fail("验证码错误");
        }
        User user = new User();
        user.setAccount(account);
        user.setNickName(nickName);
        user.setEmail(email);
        user.setPassword(Md5Util.getMD5String(password));
        userMapper.insert(user);
        return Result.ok();
    }



    @Override
    public Result<String> sendEmail(String email) {
        if (StringUtils.isBlank(email)) {
            throw new RuntimeException("未填写收件人邮箱");
        }
        // 定义Redis的key
        String key = "msg_" + email;

        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String verifyCode = valueOperations.get(key);
        if (verifyCode == null) {
            // 随机生成一个6位数字型的字符串
            String code = verifyCodeUtil.generateVerifyCode(6);
            // 邮件对象（邮件模板，根据自身业务修改）
            SimpleMailMessage message = new SimpleMailMessage();
            // message.setFrom("879406927@qq.com");
            message.setSubject("麟龙邮箱验证码");
            message.setText("尊敬的用户您好!\n\n尊敬的: " + email + "您的校验验证码为: " + code + ",有效期5分钟，请不要把验证码信息泄露给其他人,如非本人请勿操作");
            message.setTo(email);

            try {
                // 对方看到的发送人（发件人的邮箱，根据实际业务进行修改，一般填写的是企业邮箱）
                message.setFrom(new InternetAddress(MimeUtility.encodeText("麟龙邮箱验证码") + "<879406927@qq.com>").toString());
                // 发送邮件
                javaMailSender.send(message);
                // 将生成的验证码存入Redis数据库中，并设置过期时间
                valueOperations.set(key, code, 5L, TimeUnit.MINUTES);
                log.info("邮件发送成功");
                return Result.ok("邮件发送成功");
            } catch (Exception e) {
                log.error("邮件发送出现异常");
                log.error("异常信息为" + e.getMessage());
                log.error("异常堆栈信息为-->");
                return Result.fail("邮件发送失败");
            }
        } else {
            return Result.fail("验证码已发送至您的邮箱，请注意查收");
        }

    }



}

